import React, { useState } from 'react';
import { Button, Space, Modal, message } from 'antd';
import request from '@/utils/request';
import DataReleaseModal from '@/components/DataReleaseModal';
import { useNavigate } from 'react-router-dom';

const DataTableActions = ({
  advanced,
  selectedRowKeys,
  setSelectedRowKeys,
  dataKey,
  tableData,
  filterParams,
  dataLevel,
  fetchTableData,
  fetchDataLevel,
  fetchFilterOptions,
  refreshDownloadingCount
}) => {
  const [downloadLoading, setDownloadLoading] = useState(false);
  const [downloadAllLoading, setDownloadAllLoading] = useState(false);
  const [releaseModalOpen, setReleaseModalOpen] = useState(false);
  const [releaseType, setReleaseType] = useState(1);
  const navigate = useNavigate();

  // 选中数据转为接口格式
  const getSelectedFiles = () =>
    selectedRowKeys
      .map((key) => {
        const item = tableData.find((d) => d.key === key);
        return item ? { data_type: item.data_type, product_id: item.key } : null;
      })
      .filter((item) => item !== null);

  // 批量下载
  const handleBatchDownload = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要下载的数据');
      return;
    }
    setDownloadLoading(true);
    try {
      const payload = {
        query_params: {
          data_key: dataKey,
          ...filterParams
        },
        is_favorites: false,
        files: selectedRowKeys.map((key) => ({
          data_type: tableData.find((item) => item.key === key)?.data_type,
          product_id: key
        }))
      };
      const response = await request.post('/Management/DownloadOrder', payload);
      if (response.status === 200) {
        message.success('请到"下载订单"中查看拟下载数据的准备情况', 5);
        setSelectedRowKeys([]);
        try { refreshDownloadingCount && refreshDownloadingCount(); } catch(e) {}
      }
    } catch (error) {
      message.error(error?.message || '创建下载订单失败');
    } finally {
      setDownloadLoading(false);
    }
  };

  // 全部下载
  const handleDownloadAll = async () => {
    setDownloadAllLoading(true);
    try {
      const response = await request.get(advanced ? '/Management/AdvancedDataDownloadAll' : '/Management/DownloadOrderListAll', {
        params: {
          data_key: dataKey,
          ...filterParams,
          data_level: dataLevel
        }
      });
      if (response.status === 200) {
        message.success('请到"下载订单"中查看拟下载数据的准备情况', 5);
        try { refreshDownloadingCount && refreshDownloadingCount(); } catch(e) {}
      }
    } catch (error) {
      message.error(error?.message || '创建下载订单失败');
    } finally {
      setDownloadAllLoading(false);
    }
  };

  // 批量收藏
  const handleBatchFavorite = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要收藏的数据');
      return;
    }
    try {
      const payload = {
        files: selectedRowKeys.map((key) => ({
          data_type: tableData.find((item) => item.key === key)?.data_type,
          product_id: key
        }))
      };
      const response = await request.post('/Management/Favorites', payload);
      if (response.status === 200) {
        message.success('批量收藏成功');
        setSelectedRowKeys([]);
        fetchTableData && fetchTableData();
      }
    } catch (error) {
      message.error(error?.message || '收藏失败');
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的数据');
      return;
    }
    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 条数据吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const payload = {
            files: selectedRowKeys.map((key) => ({
              data_type: tableData.find((item) => item.key === key)?.data_type,
              product_id: key
            }))
          };
          const response = await request.post('/Management/DataDelete', payload);
          if (response.status === 200) {
            message.success('批量删除成功');
            setSelectedRowKeys([]);
            fetchTableData && fetchTableData();
            fetchDataLevel && fetchDataLevel();
            fetchFilterOptions && fetchFilterOptions();
          }
        } catch (error) {
          message.error(error?.message || '删除失败');
        }
      }
    });
  };

  // 批量取消发布
  const handleBatchCancelRelease = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要取消发布的数据');
      return;
    }
    Modal.confirm({
      title: '确认批量取消发布',
      content: `确定要取消发布选中的 ${selectedRowKeys.length} 条数据吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const payload = {
            files: selectedRowKeys.map((key) => ({
              data_type: tableData.find((item) => item.key === key)?.data_type,
              product_id: key
            }))
          };
          const response = await request.post('/Management/DataCancelRelease', payload);
          if (response.status === 200) {
            message.success('批量取消发布成功');
            setSelectedRowKeys([]);
            fetchTableData && fetchTableData();
          }
        } catch (error) {
          message.error(error?.message || '取消发布失败');
        }
      }
    });
  };

  // 发布弹窗
  const handleRelease = (type) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要发布的数据');
      return;
    }
    setReleaseType(type);
    setReleaseModalOpen(true);
  };

  return (
    <>
      <Space>
        <Button type="primary" loading={downloadLoading} onClick={handleBatchDownload}>
          批量下载
        </Button>
        <Button type="primary" loading={downloadAllLoading} onClick={handleDownloadAll}>
          全部下载
        </Button>
        <Button type="primary" onClick={handleBatchFavorite}>
          批量收藏
        </Button>
      </Space>
      <DataReleaseModal
        open={releaseModalOpen}
        onCancel={() => setReleaseModalOpen(false)}
        releaseType={releaseType}
        files={getSelectedFiles()}
        onSuccess={() => {
          setReleaseModalOpen(false);
          fetchTableData && fetchTableData();
        }}
      />
    </>
  );
};

export default DataTableActions; 